<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户简称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入客户简称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


        <el-form-item label="付款方式" prop="payType">
          <el-select v-model="queryParams.payType" placeholder="请选择付款方式" clearable>
            <el-option
              v-for="dict in dict.type.pay_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="queryParams.remark"
            placeholder="请输入备注"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>


        <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['baseMain:custom:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['baseMain:custom:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['baseMain:custom:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['baseMain:custom:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" label="客户基本信息">
        <el-table-column label="甲方主体" align="center" prop="aparty" />
        <el-table-column label="主合同" align="center" prop="mainParty" />
        <el-table-column label="客户简称" align="center" prop="nickName" />
        <el-table-column label="客户类别" align="center" prop="channel" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.channel" :value="scope.row.channel"/>
          </template>
        </el-table-column>
        <el-table-column label="合作方式" align="center" prop="cooperateType" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.cooperate_type" :value="scope.row.cooperateType"/>
          </template>
        </el-table-column>
        <el-table-column label="付款方式" align="center" prop="payType" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.pay_type" :value="scope.row.payType"/>
          </template>
        </el-table-column>

        <el-table-column label="乙方主体" align="center" prop="bparty" />
        <el-table-column label="合同号" align="center" prop="contractNo" />
        <el-table-column label="合同开始时间" align="center" prop="contractStartTime" />
        <el-table-column label="合同结束时间" align="center" prop="contractEndTime" />
        <el-table-column label="签署状态" align="center" prop="signs"  />
        <el-table-column label="客户类型" align="center" prop="customType"  />
        <el-table-column label="审批状态" align="center" prop="status" >
          <template slot-scope="scope">
            <el-tag size="medium" v-if=" scope.row.status == 1">生效</el-tag>
            <el-tag size="medium" type="success" v-if=" scope.row.status == 2">审批中</el-tag>
            <el-tag size="medium" type="danger" v-if=" scope.row.status == 3">审批拒绝</el-tag>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="客户归属信息">
        <el-table-column label="业务部门" align="center" prop="businessUnitName" />
        <el-table-column label="销售人员" align="center" prop="saleUserName" />
      </el-table-column>
      <el-table-column width="180px" label="操作"  fixed="right"  align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['baseMain:custom:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.signs == '未签署' && scope.row.status == 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="signUpdate(scope.row)"
          >签署审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['baseMain:custom:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户简称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入客户简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主合同" prop="mainParty">
              <el-input v-model="form.mainParty" placeholder="请输入主合同" />
            </el-form-item>
          </el-col>


        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="甲方主体" prop="aparty">
              <el-input v-model="form.aparty" placeholder="请输入甲方主体" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方主体" prop="bparty">
              <el-select style="width: 100%" v-model="form.bparty" placeholder="请选择乙方主体" clearable>
                <el-option
                  v-for="dict in dict.type.bparty"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


     <el-row>
          <el-col :span="12">
            <el-form-item label="合作方式" prop="cooperateType">
              <el-select style="width: 100%" v-model="form.cooperateType" placeholder="请选择合作方式">
                <el-option
                  v-for="dict in dict.type.cooperate_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款方式" prop="payType">
              <el-select style="width: 100%" v-model="form.payType" placeholder="请选择付款方式">
                <el-option
                  v-for="dict in dict.type.pay_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="合同开始时间" prop="contractStartTime">
              <el-date-picker style="width: 100%" clearable
                              v-model="form.contractStartTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择合同开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同结束时间" prop="contractEndTime">
              <el-date-picker style="width: 100%" clearable
                              v-model="form.contractEndTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择合同结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户类别" prop="channel">
              <el-select style="width: 100%" v-model="form.channel" placeholder="请选择客户类别" clearable>
                <el-option
                  v-for="dict in dict.type.channel"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同号" prop="contractNo">
              <el-input v-model="form.contractNo" placeholder="请输入合同号" />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>

          <el-col :span="12">
            <el-form-item label="客户类型" prop="customType">
              <el-select style="width: 100%" v-model="form.customType" placeholder="请选择客户类型">
                <el-option
                  v-for="dict in dict.type.custom_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>




          <el-col v-if="form.customType=='潜在客户'" :span="12">
            <el-form-item label="签署状态" prop="payType">
              <el-select style="width: 100%" v-model="form.signs" placeholder="请选择签署状态">
                <el-option
                  v-for="dict in dict.type.signs"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>

<!--          <el-col :span="12">-->
<!--            <el-form-item label="合同" prop="contractFile">-->
<!--              <el-link :href="'http://8.138.134.68:9002/contractFile/'+form.contractFile" v-if="form.contractFile!=null||form.contractFile!=''" type="primary">{{form.contractFile}}</el-link>-->
<!--              <el-upload-->
<!--                class="upload"-->
<!--                ref="upflieload"-->
<!--                :headers="upload.headers"-->
<!--                :action="upload.url + '?updateSupport=' + upload.updateSupport"-->
<!--                :disabled="upload.isUploading"-->
<!--                :on-preview="handlePreview"-->
<!--                :on-remove="handleRemove"-->
<!--                :on-success="handleUploadSuccess"-->
<!--                :before-remove="beforeRemove"-->
<!--                :auto-upload="true"-->
<!--                :limit="1"-->
<!--                :on-exceed="handleExceed"-->
<!--                :file-list="file">-->
<!--&lt;!&ndash;                accept=".pdf"&ndash;&gt;-->
<!--                <el-button size="small" type="primary">点击上传</el-button>-->
<!--                <div slot="tip" class="el-upload__tip">只能上传pdf文件，且不超过500kb</div>-->
<!--              </el-upload>-->
<!--            </el-form-item>-->
<!--          </el-col>-->


        </el-row>



        <el-row>
          <el-col :span="24">
            <el-form-item label="业务部门" prop="businessUnit">
              <el-tree
                class="tree-border"
                :data="deptOptions"
                highlight-current
                default-expand-all
                ref="dept"
                @node-click="getCurrentNode"
                node-key="id"
                :current-node-key="businessUnitId"
                :default-checked-keys="[form.businessUnit]"
                :check-strictly="!form.businessUnit"
                empty-text="加载中，请稍候"
                :props="defaultProps"
              ></el-tree>
            </el-form-item>

          </el-col>

        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="销售人员" prop="saleUser" >
              <el-select style="width: 100%"  @change="saleUserChang(form.saleUser)" v-model="form.saleUser" placeholder="请选择销售人员" clearable>
                <el-option
                  v-for="sale in saleList"
                  :key="sale.userId"
                  :label="sale.nickName"
                  :value="sale.userId"
                ></el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>


        <el-row>
          <el-col :span="24">

            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listCustom, getCustom, delCustom, addCustom, updateCustom,signUpdateDo } from "@/api/baseMain/custom";
import { deptTreeSelect } from "@/api/system/role";
import { selectUserIdsByDeptId } from "@/api/system/user";
import {getToken} from "@/utils/auth";

export default {

  name: "Custom",
  dicts: ['channel','cooperate_type','pay_type','bparty','signs','custom_type'],
  data() {
    return {
      file: undefined,
      businessUnitId: undefined,
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/baseMain/custom/contractFile"
      },
      // 部门列表
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label"
      },

      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户信息表格数据
      customList: [],
      //销售人员列表
      saleList: [],
      //运营人员列表
      operateList: [],
      // 弹出层标题
      title: "",
      contractTitle: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: undefined,
        channel: undefined,
        cooperateType: undefined,
        payType: undefined,
        payment: undefined,
        mainParty: undefined,
        aparty: undefined,
        bparty: undefined,
        bidding: undefined,
        businessUnit: undefined,
        saleUser: undefined,
        customType: undefined,
      },
      // 表单参数
      form: {},
      contractForm: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键不能为空", trigger: "blur" }
        ],
        mainParty: [
          { required: true, message: "主合同不能为空", trigger: "blur" }
        ],
        payType: [
          { required: true, message: "付款方式不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "客户简称不能为空", trigger: "blur" }
        ],

        saleUser: [
          { required: true, message: "销售人员不能为空", trigger: "blur" }
        ],
        channel: [
          { required: true, message: "客户类别不能为空", trigger: "blur" }
        ],
        aparty: [
          { required: true, message: "甲方主体不能为空", trigger: "blur" }
        ],
        bparty: [
          { required: true, message: "乙方主体不能为空", trigger: "blur" }
        ],
        cooperateType: [
          { required: true, message: "合作方式不能为空", trigger: "blur" }
        ],
        contractStartTime: [
          { required: true, message: "合同开始时间不能为空", trigger: "blur" }
        ],
        contractEndTime: [
          { required: true, message: "合同结束时间不能为空", trigger: "blur" }
        ],
        contractNo: [
          { required: true, message: "合同号不能为空", trigger: "blur" }
        ],
        signs: [
          { required: true, message: "签署状态不能为空", trigger: "blur" }
        ],
        customType: [
          { required: true, message: "客户类型不能为空", trigger: "blur" }
        ],
      }
    };
  },
  mounted() {
    this.getDeptTree();
  },
  created() {
    this.getList();
  },
  methods: {
    handleUploadSuccess(res, file) {

  // 如果上传成功
  if (res.code == 200) {
    // 获取光标所在位置
    this.form.contractFile = res.data
    } else {
      this.$message.error(res.msg);
    }
  },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    // 根据部门查询 部门下的对应角色
    getCurrentNode(e){
      this.form.businessUnit = e.id
      this.form.businessUnitName = e.label

      let sale = {
        roleId : '1741717661796728834',
        deptId : e.id
      }
      // 查询销售人员
      selectUserIdsByDeptId(sale).then(response =>{
        this.saleList = response.data
        if(this.saleList.length == 0){
          this.form.saleUserName = null
          this.form.saleUser = null
        }
      })
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTree() {
      return deptTreeSelect(1).then(response => {
        this.deptOptions = response.data.depts;
        return response;
      });
    },

    saleUserChang(e){
      for (let index in this.saleList){
        if(this.saleList[index].userId == e){
          this.form.saleUserName = this.saleList[index].nickName
        }
      }
    },

    /** 查询客户信息列表 */
    getList() {
      this.loading = true;
      listCustom(this.queryParams).then(response => {
        this.customList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        nickName: undefined,
        channel: undefined,
        signs: undefined,
        cooperateType: undefined,
        payType: undefined,
        mainParty: undefined,
        aparty: undefined,
        bparty: undefined,
        businessUnit: undefined,
        saleUser: undefined,
        remark: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        contractFile: undefined,
        customType: undefined,
        updateBy: undefined
      };

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getDeptTree();
      this.open = true;
      this.title = "添加客户信息";
      this.$refs.upflieload.clearFiles()
    },
    signUpdateDo(id){
      signUpdateDo(id).then(response => {
        this.$modal.msgSuccess("提交成功");
      })
    },
    signUpdate(row){
      this.$modal.confirm('是否确认提交补签合同').then(() => {
        this.loading = true;
        return this.signUpdateDo(row.id);
      }).then(() => {
        this.loading = false;
        this.getList();
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getDeptTree();
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCustom(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.businessUnitId = response.data.businessUnit;
        this.open = true;
        this.title = "修改客户信息";
        this.$nextTick(() => {
          this.$refs['dept'].setCurrentKey(this.businessUnitId);
        });
        this.getCurrentNode(this.form.businessUnit)
      });

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if(this.form.customType != '潜在客户'){
            this.form.signs = '已签署'
          }
          if (this.form.id != null) {
            updateCustom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addCustom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户信息编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delCustom(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('baseMain/custom/export', {
        ...this.queryParams
      }, `custom_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
